import store from '@/store/'
import { getStore } from '@/util/store'
import { redirectLogin } from '@/util/redirect'
import { getToken, getTokenConfigObj } from '@/util/auth'

// 过滤刷新token的url
const noCheckRefreshUrl = ['/yitu-service-auth-api/oauth2/refreshToken', '/yitu-auth/oauth/token', '/yitu-auth/oauth/captcha']

// 存储请求的数组
let cacheRequestArr = []

let refreshLock = false

function isRefreshLock() {
  return refreshLock
}

// 将所有的请求都push到数组中
function cacheRequestArrHandle(config) {
  console.log(config)
  const retry = new Promise((resolve) => {
    cacheRequestArr.push(() => {
      const tokenConfigObj = getTokenConfigObj()
      config.headers[tokenConfigObj.tokenName] = tokenConfigObj.tokenPrefix + ' ' + getToken()

      // 将请求挂起
      resolve(config)
    })
  })
  return retry
}
// 重新发起请求
function afreshRequest() {
  cacheRequestArr.map(cb => cb())
  cacheRequestArr = []
}

// 刷新token顺延
function refreshToken(config) {
  const url = config.url.replace('/api', '')
  if (noCheckRefreshUrl.includes(url)) {
    return config
  }
  if (!getToken()) {
    return config
  }
  if (refreshLock) {
    // 返回一个Promise
    return cacheRequestArrHandle(config)
  }
  // if (isTokenExpired()) {
  //   refreshLock = true
  //   store.dispatch('refreshToken').then(() => {
  //     // 重新发起未发送出去的请求
  //     afreshRequest()
  //   }).catch(() => {
  //     cacheRequestArr = []
  //     redirectLogin()
  //   }).finally(() => {
  //     refreshLock = false
  //   })
  //   return cacheRequestArrHandle(config)
  // }
  return config
}
// 判断token是否过期
/**
 * 刷新机制：请求接口时间距离上次刷新token时间(第一次是登录时间)超过token有效期的一半时进行token刷新token
 * @returns
 */
function isTokenExpired() {
  const curTime = new Date().getTime()
  const time = Number((curTime - getRefreshTime()) / 1000)
  const expiresIn = getExpiresIn() / 2
  return time > expiresIn
}
/**
 * 获取token过期时长
 * @returns
 */
function getExpiresIn() {
  const userInfo = store.getters.userInfo
  return userInfo.expiresIn || 0
}
/**
 * 获取最后一次刷新tonken时间
 * @returns
 */
function getRefreshTime() {
  const obj = getStore({ name: 'refreshToken', debug: true })
  return obj && Object.keys(obj).length > 0 ? obj.datetime : 0
}

export {
  isRefreshLock,
  isTokenExpired,
  refreshToken
}
